package com.example.travelservlet.oss.service;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClient;
import com.example.travelservlet.util.ConstantUtil;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.xml.crypto.Data;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

/**
 * @author hxy
 * @date 2023/5/15 15:04
 */
@Service
public class OssServiceImpl implements OssService {
    @Override
    public String uploadOssFile(MultipartFile file) {
        String endpoint = ConstantUtil.END_POINT;
        String accessKeyId = ConstantUtil.ACCESS_KEY_ID;
        String accessKeySecret = ConstantUtil.ACCESS_KEY_SECRET;
        String bucketName = ConstantUtil.BUCKET_NAME;

        OSS ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);

        try {
            InputStream inputStream = file.getInputStream();
            String filename = file.getOriginalFilename();

            String uuid = UUID.randomUUID().toString().replace("-", "");
            filename = uuid +filename;

            String datePath = new DateTime().toString("yyyy-MM-dd");
            filename = datePath+"/"+filename;

            ossClient.putObject(bucketName, filename, inputStream);
            ossClient.shutdown();
            String url = "https://" + bucketName + "." + endpoint + "/" + filename;
            return url;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }


}
